package com.xhh.nphm.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhh.nphm.common.annotation.RepeatSubmit;
import com.xhh.nphm.common.constant.Constants;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.QueryConditionVo;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.*;
import com.xhh.nphm.common.utils.file.FileTools;
import com.xhh.nphm.common.utils.poi.ExcelUtil;
import com.xhh.nphm.system.domain.*;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.service.MMailWorkFormLogService;
import com.xhh.nphm.system.service.MmailWorkFormService;
import com.xhh.nphm.system.service.MwfSendBackService;
import com.xhh.nphm.system.service.OpmCrowdService;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import com.xhh.nphm.system.service.impl.MailGetDealServiceImpl;
import com.xhh.nphm.system.vo.ApprovalVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/wsMail/")
public class MmailGetDealController extends BaseController {
    private String prefix = "system/wsMail";
    @Autowired
    private MailGetDealServiceImpl mailGetDealService;
    @Autowired
    private MMailWorkFormLogService mMailWorkFormLogService;
    @Autowired
    private CommonServiceImpl commonService;
    @Autowired
    private OpmCrowdService opmCrowdService;
    @Autowired
    private MmailWorkFormService mmailWorkFormService;
    @Autowired
    private MwfSendBackService mwfSendBackService;
    @Autowired
    private AcquireWFNoUtils acquireWFNoUtils;
    @Autowired
    private MMailWFrManageController manageController;
    @Autowired
    private CommonDao commonDao;


    /**
     * 已直接回复M页面
     * @return
     */
    @RequestMapping("listOver")
    public ModelAndView listOver(){
        return new ModelAndView(prefix+"/listOver");
    }
    /**
     * 已废除信件页面
     * @return
     */
    @RequestMapping("abolish")
    public ModelAndView abolish(){
        return new ModelAndView(prefix+"/abolish");
    }
    /**
     * 已派单来信页面
     * @return
     */
    @RequestMapping("distribute")
    public ModelAndView distribute(){
        return new ModelAndView(prefix+"/distribute");
    }

    /**
     * 我受理的信件页面
     * @return
     */
    @RequestMapping("acceptance")
    public ModelAndView acceptance(){
        return new ModelAndView(prefix+"/acceptance");
    }

    /**
     * 待受理的信件页面
     * @return
     */
    @RequestMapping("wait")
    public ModelAndView listWait(){
        return new ModelAndView(prefix+"/wait");
    }

    /**
     * 信件录入列表页面
     * @return
     */
    @RequestMapping("waitMail")
    public ModelAndView waitMail(){
        return new ModelAndView(prefix+"/waitMail");
    }

    /**
     * (网络理政区县)待处理信件M列表页面
     * @return
     */
    @RequestMapping("listWaitGetXZ")
    public ModelAndView listWaitGetXZ(){
        return new ModelAndView(prefix+"/listWaitGetXZ");
    }

    /**
     * (网络理政区县)下级收到来信M列表页面
     * @return
     */
    @RequestMapping("listThirdMail")
    public ModelAndView listThirdMail(){
        return new ModelAndView(prefix+"/listThirdMail");
    }

    /**
     * (网络理政区县)已受理的信件M列表页面
     * @return
     */
    @RequestMapping("myGetListXZ")
    public ModelAndView myGetListXZ(){
        return new ModelAndView(prefix+"/myGetListXZ");
    }


    /**
     * (网络理政区县)待受理信件处理页面
     * @param id 信件id
     * @return
     */
    @RequestMapping("/mailGetDealXZ/{id}")
    public ModelAndView mailGetDealXZ(@PathVariable("id")Integer id,ModelMap map){
        map.put("mmailGetDeal",mailGetDealService.getById(id));
        return new ModelAndView(prefix+"/mailGetDealXZ");
    }

    /**
     * 已直接回复M列表
     * @param mmailGetDealEty
     * @return
     */
    @RequestMapping("mailGetDealList")
    public TableDataInfo mailGetDealList(MmailGetDealEty mmailGetDealEty){
        startPage();
        return getDataTable(mailGetDealService.getMailGetDealList(mmailGetDealEty));
    }

    /**
     * 已废除信件列表
     * @param mmailGetDealEty
     * @return
     */
    @RequestMapping("abolishList")
    public TableDataInfo abolishList(MmailGetDealEty mmailGetDealEty){
        startPage();
        return getDataTable(mailGetDealService.getAbolishList(mmailGetDealEty));
    }

    /**
     * 已派单信件列表
     * @param mmailGetDealEty
     * @return
     */
    @RequestMapping("distributeList")
    public TableDataInfo distributeList(MmailGetDealEty mmailGetDealEty){
        startPage();
        return getDataTable(mailGetDealService.getDistributeList(mmailGetDealEty));
    }

    /**
     * 我受理的信件列表
     * @param mmailGetDealEty
     * @return
     */
    @RequestMapping("acceptanceList")
    public TableDataInfo acceptanceList(MmailGetDealEty mmailGetDealEty){
        startPage();
        return getDataTable(mailGetDealService.getAcceptanceList(mmailGetDealEty));
    }

    /**
     * 待受理信件列表
     * @param mmailGetDealEty
     * @return
     */
    @RequestMapping("waitList")
    public TableDataInfo waitList(MmailGetDealEty mmailGetDealEty){
        startPage();
        return getDataTable(mailGetDealService.getWaitList(mmailGetDealEty));
    }


    /**
     * (网络理政区县)待受理信件M列表
     * @param mmailGetDealEty 查询条件
     * @return 列表数据
     */
    @RequestMapping("listWaitGetXZJson")
    public TableDataInfo listWaitGetXZJson(MmailGetDealEty mmailGetDealEty){
        startPage();
        return getDataTable(mailGetDealService.listWaitGetXZJson(mmailGetDealEty,getSysUser().getDeptId().toString()));
    }

    /**
     * (网络理政区县)待受理信件M列表
     * @param mmailGetDealEty 查询条件
     * @return 列表数据
     */
    @RequestMapping("listThirdMailJson")
    public TableDataInfo listThirdMailJson(MmailGetDealEty mmailGetDealEty){
        SysUser user = getSysUser();
        String deptNo = user.getDeptId().toString();
        if(deptNo.length() == 6 && deptNo.startsWith("304")) {
            deptNo = "301"+deptNo.substring(3,deptNo.length());
        }
        startPage();
        return getDataTable(mailGetDealService.listThirdMailJson(mmailGetDealEty, getSysUser().getAreaNo(),deptNo));
    }

    /**
     * (网络理政区县)已受理的信件M列表
     *
     * @return 列表数据
     */
    @RequestMapping("myGetListXZJson")
    public TableDataInfo myGetListXZJson(MmailGetDealEty mmailGetDealEty){
        startPage();
        return getDataTable(mailGetDealService.myGetListXZJson(mmailGetDealEty, getSysUser().getDeptId().toString()));
    }

    /**
     * 区县信件录入列表数据
     * @param mmailGetDealEty
     * @return
     */
    @RequestMapping("entryMailList")
    public TableDataInfo entryMailList(MmailGetDealEty mmailGetDealEty){
        SysUser user = getSysUser();
        mmailGetDealEty.setFmCerNo(user.getDeptId().toString());
        mmailGetDealEty.setStateFlag(1412);
        startPage();
        return getDataTable(mailGetDealService.entryMailList(mmailGetDealEty));
    }

    /**
     * 通过ids数组删除所有信件
     * @param ids
     * @return
     */
    @RequestMapping("deleteAll")
    public AjaxResult deleteAll(String... ids){
        return toAjax(mailGetDealService.deleteAll(ids));
    }

    /**
     * 编辑来信页面
     * @param pkId
     * @param map
     * @return
     */
    @RequestMapping("editMail/{id}")
    public ModelAndView editMail(@PathVariable("id") Integer pkId, ModelMap map){
        MmailGetDealEty mmailGetDealEty = mailGetDealService.selectByPkId(pkId);
        map.put("mmailGetDeal",mmailGetDealEty);
        return new ModelAndView(prefix+"/editMail");
    }

    /**
     * 来信详情页面
     * @param pkId
     * @param map
     * @return
     */
    @RequestMapping("mailGetShow/{id}")
    public ModelAndView mailDetail2(@PathVariable("id") Integer pkId, ModelMap map){
        MmailGetDealEty mmailGetDealEty = mailGetDealService.selectByPkId(pkId);
        map.put("mmailGetDeal",mmailGetDealEty);
        return new ModelAndView(prefix+"/mailGetShow");
    }

    /**
     * 信件录入-编辑来信页面
     * @param pkId 信件id
     * @param map 模型
     * @return 视图
     */
    @RequestMapping("updateLetter/{id}")
    public ModelAndView updateLetter(@PathVariable("id") Integer pkId, ModelMap map){
        MmailGetDealEty mmailGetDealEty = mailGetDealService.selectByPkId(pkId);
        SysUser user = getSysUser();
        map.put("mmailGetDeal",mmailGetDealEty);
        //存在附件，展示附件
        if(mmailGetDealEty.getYspare() != null){
            try {
                map.put("names",FileTools.getAccessoryName(mmailGetDealEty.getWsCode()));
            } catch (ServiceException | IOException e) {
                e.printStackTrace();
            }
        }
        map.put("user",user);
        return new ModelAndView(prefix+"/updateLetter");
    }

    /**
     * 编辑保存来信 直接答复
     * @param mmailGetDeal
     * @return
     */
    @RequestMapping("edit")
    public AjaxResult edit(MmailGetDealEty mmailGetDeal){
        UpdateWrapper<MmailGetDealEty> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("fmAreaNo", mmailGetDeal.getFmAreaNo());
        updateWrapper.set("fmAreaName", mmailGetDeal.getFmAreaName());
        updateWrapper.set("fromName", mmailGetDeal.getFromName());
        updateWrapper.set("fromSex", mmailGetDeal.getFromSex());
        updateWrapper.set("fmAddress", mmailGetDeal.getFmAddress());
        updateWrapper.set("fromTel", mmailGetDeal.getFromTel());
        updateWrapper.set("fromTopic", mmailGetDeal.getFromTopic());
        updateWrapper.set("fmContent", mmailGetDeal.getFmContent());
        updateWrapper.set("openFrom", mmailGetDeal.getOpenFrom());
        updateWrapper.set("stateFlag", mmailGetDeal.getStateFlag());
        updateWrapper.set("stateDesc", mmailGetDeal.getStateDesc());
        updateWrapper.set("dfmClaNo", mmailGetDeal.getDfmClaNo());
        updateWrapper.set("dfmClaName", mmailGetDeal.getDfmClaName());
        updateWrapper.set("dCntACode", mmailGetDeal.getdCntACode());
        updateWrapper.set("dCntAName", mmailGetDeal.getdCntAName());
        updateWrapper.set("openX", mmailGetDeal.getOpenX());
        updateWrapper.set("xdealDesc", mmailGetDeal.getXdealDesc());
        updateWrapper.set("repeatFlag", mmailGetDeal.getRepeatFlag());
        updateWrapper.set("isAutoExtend",mmailGetDeal.getIsAutoExtend());
        //1611 直接答复
        if(mmailGetDeal.getStateFlag()==1611){
            updateWrapper.set("yworker",getSysUser().getUserName());
            updateWrapper.set("yworkno",getSysUser().getUserNo());
            updateWrapper.set("ydealDesc",mmailGetDeal.getXdealDesc());
            updateWrapper.set("yeditTime",DateUtils.getNowDate());
        }
        updateWrapper.eq("pkId", mmailGetDeal.getPkId());
        boolean flag = mailGetDealService.update(updateWrapper);
        return toAjax(flag);
    }

    /**
     * 进入信件录入页面
     * @return 视图
     */
    @GetMapping("letterEntry")
    public ModelAndView letterEntry(ModelMap model){
        SysUser user = getSysUser();
        model.addAttribute("user", user);
        return new ModelAndView(prefix+"/letterEntry");
    }




    /**
     * 新增信件
     */
    @PostMapping("/addMail")
    public AjaxResult addMail(MmailGetDealEty mmailGetDealEty, HttpServletRequest request, MultipartFile[] files){
//        Date date = DateUtils.getNowDate();
        SysUser user = getSysUser();
        String tmp = "";
        tmp = commonService.makeRandomStr(6);
        mmailGetDealEty.setWsKey(tmp);//提取码
        if(acquireWFNoUtils.isEnable()){
            String wsCode = acquireWFNoUtils.getMailWsCode();
            if(Objects.equals(wsCode, "")){
                tmp = byTelGetSN(5);
                acquireWFNoUtils.renewValue(Constants.MAIL_CODE_COUNT_KEY);
            }else{
                tmp = wsCode;
            }
//            tmp = Objects.equals(wsCode, "") ? byTelGetSN(5) : wsCode;
        }else{
            tmp = byTelGetSN(5);
        }
        mmailGetDealEty.setWsCode(tmp);//流水号
//        mmailGetDealEty.setLiftWorkNo(user.getUserNo());
//        mmailGetDealEty.setLiftWorker(user.getUserName());
//        mmailGetDealEty.setYworkNo(user.getUserNo());
//        mmailGetDealEty.setYworker(user.getUserName());
        mmailGetDealEty.setFmCerName(user.getDeptName());
        mmailGetDealEty.setFmCerNo(user.getDeptId().toString());
        mmailGetDealEty.setPkId(0);
        mmailGetDealEty.setAutoGetFlag(-1);
        mmailGetDealEty.setStateFlag(1412);
        mmailGetDealEty.setStateDesc("未处理");
        mmailGetDealEty.setLiftInt(0);
        mmailGetDealEty.setIsDel(0);
        mmailGetDealEty.setSpareInt(0);
        mmailGetDealEty.setFkint(0);
        mmailGetDealEty.setFlagInt(0);
//        mmailGetDealEty.setYeditTime(date);
//        mmailGetDealEty.setFromTime(date);
        mmailGetDealEty.setFromName(mmailGetDealEty.getFromName());
        mmailGetDealEty.setFmAttachP(getIpAddr(request));
        boolean flag = mailGetDealService.saveOrUpdate(mmailGetDealEty);
        //判断是否存在附件
        if(files.length > 0){
            String yspare = "";
            //上传附件
            for (int i = 0; i < files.length; i++) {
                if(files[i] == null || files[i].isEmpty()) {
                    continue;
                }
                byte[] bytes = new byte[0];//获得图片数组
                try {
                    bytes = files[i].getBytes();
                    yspare = FileTools.savaImg(mmailGetDealEty.getWsCode(),bytes,files[i].getOriginalFilename());
                } catch (IOException | ServiceException e) {
                    e.printStackTrace();
                }
            }
            UpdateWrapper<MmailGetDealEty> updateWrap = new UpdateWrapper<>();
            updateWrap.set("YSpare",yspare);
            updateWrap.eq("PkId",mmailGetDealEty.getPkId());
            mailGetDealService.update(updateWrap);
        }
        return toAjax(flag);
    }

    /**
     * 信件 处理页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/handleMail/{id}")
    public ModelAndView handleMail(@PathVariable("id") Integer pkId, ModelMap map) {
        MmailGetDealEty mmailGetDealEty = mailGetDealService.selectByPkId(pkId);
        SysUser user = ShiroUtils.getSysUser();
        mmailGetDealEty.setYworker(user.getUserName());
        mmailGetDealEty.setYworkNo(user.getUserNo());
        map.put("mmailGetDeal", mmailGetDealEty);
        return new ModelAndView(prefix+"/handleMail");
    }


    /**
     * 创建工单
     *
     * @param mmailGetDealEty
     * @return
     */
    @PostMapping("createWorkform")
    @RepeatSubmit
    public Object createWorkform(MmailGetDealEty mmailGetDealEty) throws ParseException {
        // TODO: openx和openFrom不清楚页面怎么修改  OriginFlag默认为110
        SysUser user = ShiroUtils.getSysUser();
        // 修改来信记录
        MmailGetDealEty oldMail = mailGetDealService.selectByPkId(mmailGetDealEty.getPkId());

        // 把来信记录复制给信件工单 并新增信件工单
        MmailWorkForm mmailWorkForm = new MmailWorkForm();
        mmailWorkForm.setFlagString(oldMail.getFlagString());
        mmailWorkForm.setWsUFlag(0);
        // mmailWorkForm.setFromTime(oldMail.getXinputTime());
        mmailWorkForm.setFromTime(oldMail.getFromTime());
        mmailWorkForm.setFmSpareB(oldMail.getYspare());
        mmailWorkForm.setFKInt(oldMail.getFkint());
        //是否摘报 默认为否0
        mmailWorkForm.setRecordFlag(0);
        mmailWorkForm.setFlagInt(oldMail.getFlagInt());

        mmailWorkForm.setFromTel(mmailGetDealEty.getFromTel());
        mmailWorkForm.setFromTopic(mmailGetDealEty.getFromTopic());
        mmailWorkForm.setSpareInt(oldMail.getSpareInt());
        mmailWorkForm.setFmContent(mmailGetDealEty.getFmContent());
        mmailWorkForm.setFmCerName(oldMail.getFmCerName());
        mmailWorkForm.setFmCerNO(oldMail.getFmCerNo());
        mmailWorkForm.setFromSex(mmailGetDealEty.getFromSex());
        mmailWorkForm.setFmEmail(oldMail.getFmEmail());
        mmailWorkForm.setFmSpareB(oldMail.getFmSpare());
        mmailWorkForm.setSpareString(oldMail.getSpareString());
        mmailWorkForm.setFromName(mmailGetDealEty.getFromName());
        mmailWorkForm.setWsCode(mmailGetDealEty.getWsCode());
        mmailWorkForm.setWsKey(mmailGetDealEty.getWsKey());
        mmailWorkForm.setDcntACode(mmailGetDealEty.getdCntACode());
        mmailWorkForm.setDcntAName(mmailGetDealEty.getdCntAName());
        mmailWorkForm.setDfmClaNo(mmailGetDealEty.getDfmClaNo());
        mmailWorkForm.setDfmClaName(mmailGetDealEty.getDfmClaName());
        mmailWorkForm.setOriginFK(mmailGetDealEty.getPkId()+"");
        mmailWorkForm.setFmAddress(mmailGetDealEty.getFmAddress());
        mmailWorkForm.setFmAreaNo(oldMail.getFmAreaNo());
        mmailWorkForm.setFmAreaName(oldMail.getFmAreaName());
        mmailWorkForm.setOpenFrom(mmailGetDealEty.getOpenFrom());
        mmailWorkForm.setOpenX(mmailGetDealEty.getOpenFrom());
        // 设置创建工单的人
        mmailWorkForm.setIptWorker(user.getUserName());
        mmailWorkForm.setIptWorkNo(user.getUserNo());
        // 设置工单创建时间
        mmailWorkForm.setIptTime(new Date());
        // 信件标记
        mmailWorkForm.setOriginFlag(210);
        mmailWorkForm.setCrtStepTime(new Date());
        mmailWorkForm.setCrtStepId(100);
        mmailWorkForm.setCrtStepName("初稿");
        // 设置工单性质为普通工单
        mmailWorkForm.setSetProId(11);
        mmailWorkForm.setSetProName("普通工单");
        String workFormNo;
        if (acquireWFNoUtils.isEnable()){
            String mailWFNo = acquireWFNoUtils.getMailWFNo();
            if(Objects.equals(mailWFNo,"")){
                workFormNo = commonService.byMWFGetNO(5);
                acquireWFNoUtils.renewValue(Constants.MAIL_NO_COUNT_KEY);
            }else {
                workFormNo = mailWFNo;
            }
        }else{
            workFormNo = commonService.byMWFGetNO(5);
        }
        mmailWorkForm.setWorkFormNo(workFormNo);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date myTmLmt = format.parse(commonService.getNxetBackLimit(5));
        mmailWorkForm.setWfLimit(myTmLmt);
        mmailWorkForm.setWfDefer(myTmLmt);
        int rows = 0;
        boolean flag = mmailWorkFormService.save(mmailWorkForm);

        // 记录信件工单操作日志
        if (flag) {
            rows = 1;
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(Integer.parseInt(mmailWorkForm.getPkId()));
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            // etyLog.setLogTime(new Date()); //不设置使用数据库默认值
            etyLog.setOpAction("创建");
            etyLog.setOpBtnID(-1);
            etyLog.setWsDesc("创建工单");
            etyLog.setWsOpen(0);
            etyLog.setOpDesc("创建工单");
            etyLog.setEffectFlag(-1);
            mMailWorkFormLogService.save(etyLog);

            // 反向更新信件记录
            if (oldMail != null) {
                oldMail.setYworkNo(user.getUserNo());
                oldMail.setYworker(user.getUserName());
                oldMail.setYdealDesc("创建工单");
                oldMail.setYsysDesc("创建工单");
                oldMail.setWkPkId(Integer.parseInt(mmailWorkForm.getPkId()));
                oldMail.setWkFmNo(mmailWorkForm.getWorkFormNo());
                // TODO 一级部门155 二级部门1551
                int oriLevel = 1;
                String deptNo = "";
                if (user != null) {
                    deptNo = String.valueOf(user.getDeptId());
                    if ((deptNo.length() == 3) && (!deptNo.equals("304"))) {
                        oriLevel = 2;
                    }
                    else if ((deptNo.length() == 6) && (deptNo.startsWith("304"))) {
                        oriLevel = deptNo.length() / 3;
                    }
                    else if(deptNo.length() > 6) {
                        oldMail.setStateFlag(1551);
                    }
                }
                if (oriLevel == 1) {
                    oldMail.setStateFlag(155);
                }
                else if (oriLevel == 2) {
                    oldMail.setStateFlag(1551);
                }
                oldMail.setStateDesc("转入工单处理");
                oldMail.setAutoGetFlag(0);
//                oldMail.setOpenX(mmailWorkForm.getOpenX());
                mailGetDealService.updateMail(oldMail);
            }
        }
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("pkId", mmailWorkForm.getPkId());
        ajaxResult.put("msg", "操作成功");
        ajaxResult.put("code", 0);
        return ajaxResult;
    }


    /**
     * 创建工单 页面
     *
     * @param
     * @param map
     * @return
     */
    @GetMapping("/tworkform/{pkId}")
    public ModelAndView workform(@PathVariable("pkId") Integer pkId, ModelMap map) {
        MmailWorkForm mmailWorkForm = mmailWorkFormService.getById(pkId);
        if (mmailWorkForm != null) {
            MmailGetDealEty mmailGetDeal = mailGetDealService.selectByPkId(Integer.parseInt(mmailWorkForm.getOriginFK()));
            map.put("workFormBase", mmailWorkForm);
            map.put("mmailGetDeal", mmailGetDeal);
        }
        return new ModelAndView(prefix+"/mworkformadd");
    }

    /**
     * 通过工单
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("pass")
    @RepeatSubmit
    public AjaxResult pass(MmailWorkForm mmailWorkForm) {
        MmailWorkForm workForm = mmailWorkFormService.getById(mmailWorkForm.getPkId());
        List<MwfSendBack> twfSendBackEties = mwfSendBackService.selectByWfId(workForm.getPkId());
        UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
        if (twfSendBackEties.size() > 0) {
            updateWrapper.eq("PkId", workForm.getPkId());
            updateWrapper.set("CrtStepID", 103);
            updateWrapper.set("CrtStepName", "审查工单");
            updateWrapper.set("CrtStepTime", new Date());
        } else {
            updateWrapper.eq("PkId", workForm.getPkId());
            updateWrapper.set("CrtStepID", 100);
            updateWrapper.set("CrtStepName", "初稿");
            updateWrapper.set("CrtStepTime", new Date());
        }
        return toAjax(mmailWorkFormService.update(null, updateWrapper));
    }

    /**
     * 通过并派单
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("dispatch")
    @RepeatSubmit
    public AjaxResult dispatch(MmailWorkForm mmailWorkForm) {
        //保存响应结果
        boolean flag = false;
        //校验方法入参是否为空
        if (mmailWorkForm != null) {
            SysUser user = ShiroUtils.getSysUser();
            UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("PkId", mmailWorkForm.getPkId());
            updateWrapper.set("CrtStepID", mmailWorkForm.getCrtStepId());
            updateWrapper.set("CrtStepName", mmailWorkForm.getCrtStepName());
            updateWrapper.set("WsUFlag", 1);
            updateWrapper.set("IptWorkNo", user.getUserNo());
            updateWrapper.set("IptWorker", user.getUserName());
            //修改工单信息
            flag = mmailWorkFormService.update(null, updateWrapper);
            //封装工单操作日志
            dispatchTwfLog(mmailWorkForm, user);
            //更新电话记录和工单操作日志
            if (Integer.parseInt(mmailWorkForm.getOriginFK())>0) {
                MmailGetDealEty ttelGetDealEty = mailGetDealService.selectByPkId(Integer.parseInt(mmailWorkForm.getOriginFK()));
                UpdateWrapper<MmailGetDealEty> wrapper = new UpdateWrapper<>();
                wrapper.eq("PkId", mmailWorkForm.getOriginFK());
                wrapper.set("OpenX", mmailWorkForm.getOpenX());
                wrapper.set("StateDesc", "审定工单");
                wrapper.set("AutoGetFlag", 0);
                mailGetDealService.update(null, wrapper);
            }
            //封装OpmCrowd记录
            OpmCrowd opmCrowd = dispatchOpmCrowd(mmailWorkForm, user);
            //新增OpmCrowd记录
            opmCrowdService.save(opmCrowd);
        }
        return toAjax(flag);
    }


    /**
     * 通过并派单-封装工单操作日志
     *
     * @param mmailWorkForm 工单信息
     * @param user             当前登录用户
     */
    private void dispatchTwfLog(MmailWorkForm mmailWorkForm, SysUser user) {
        //封装工单操作日志
        MMailWorkFormLog mmailWorkLogEty = new MMailWorkFormLog();
        //[tWorkFormBase]PkId
        mmailWorkLogEty.setWfId(Integer.parseInt(mmailWorkForm.getPkId()));
        mmailWorkLogEty.setOpDeptNo(user.getDeptId().toString());
        mmailWorkLogEty.setOpDeptName(user.getDeptName());
        mmailWorkLogEty.setOpUserNo(user.getUserNo());
        mmailWorkLogEty.setOpUserName(user.getUserName());
        mmailWorkLogEty.setOpAction("审核工单");
        mmailWorkLogEty.setOpBtnID(-1);
        mmailWorkLogEty.setWsDesc("派发工单");
        mmailWorkLogEty.setWsOpen(0);
        mmailWorkLogEty.setOpDesc("审核工单");
        mmailWorkLogEty.setEffectFlag(-1);
        mMailWorkFormLogService.save(mmailWorkLogEty);
    }

    /**
     * 通过并派单-封装OpmCrowd记录
     *
     * @param mmailWorkForm 工单信息
     * @param user             当前登录用户信息
     * @return opmCrowd对象
     */
    private OpmCrowd dispatchOpmCrowd(MmailWorkForm mmailWorkForm, SysUser user) {
        OpmCrowd opmCrowd = new OpmCrowd();
        String msg = "成都12345温馨提示：您的来信已受理（流水号：{0}；提取码：{1}），可以通过网站（http://12345.chengdu.gov.cn）进行查询，谢谢。";
        msg = msg.replace("{0}", mmailWorkForm.getWsCode()).replace("{1}", mmailWorkForm.getWsKey());
        //电话单
        opmCrowd.setFlagOrigin(11);
        opmCrowd.setWorkFormPK(Integer.parseInt(mmailWorkForm.getPkId()));
        opmCrowd.setIptUserNo(user.getUserNo());
        opmCrowd.setIptWorker(user.getUserName());
        opmCrowd.setIptTime(new Date());
        //create
        opmCrowd.setFlagSort("101");
        opmCrowd.setMsgPhone(mmailWorkForm.getFromTel());
        opmCrowd.setMsgCnnt(msg);
        opmCrowd.setMsgSign("");
        //wait send
        opmCrowd.setFlagSend(0);
        return opmCrowd;
    }



    /**
     * 拟办部门页面
     *
     * @param
     * @param
     * @return
     */
    @GetMapping("/proposed/{pkId}")
    public ModelAndView proposed(@PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        MmailWorkForm mmailWorkForm = mmailWorkFormService.getById(pkId);
        MwfSendBack sendBackEty = new MwfSendBack();
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        map.put("mmailWorkForm", mmailWorkForm);
        map.put("wfId", mmailWorkForm.getPkId());
        map.put("mailPk", mmailWorkForm.getOriginFK());
        map.put("sdeptName", user.getDept().getDeptShort());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());
        map.put("deptId", user.getDeptId());

        map.put("sendTime", DateUtils.getTime());
        return new ModelAndView(prefix+"/deptdiag");
    }


    /**
     * 拟派工单
     *
     * @param
     * @return
     */
    @RequestMapping("simulacrum")
    @RepeatSubmit
    public AjaxResult simulacrum(MwfSendBack mwfSendBack, String zpFlag){
        if (IS_GAOXIN()){
            return simulacrum_gxq(mwfSendBack,zpFlag);
        }else{
            return simulacrum_general(mwfSendBack);
        }
    }


    public AjaxResult simulacrum_general(MwfSendBack mwfSendBack) {
        String deptId = getSysUser().getDeptId().toString();
        MwfSendBack sbQX = new MwfSendBack(); //区县政府
        if (mwfSendBack.getFpDirect() == 1) {//xnb直派 给区县初始化一条记录
            sbQX.setMailPk(mwfSendBack.getMailPk());
            sbQX.setWfId(mwfSendBack.getWfId());
            int oriLevel = 1;
            if(!"304".equals(deptId) && deptId.length() == 3)
                oriLevel = 2;
            else
                oriLevel = deptId.length() / 3;
            sbQX.setOriLevel(oriLevel);
            sbQX.setSeqCode(mwfSendBack.getSeqCode());
            sbQX.setSeqName(mwfSendBack.getSeqName());
            sbQX.setSendState(23);  //已派下级
            sbQX.setSortCode(mwfSendBack.getSortCode());
            sbQX.setSortName(mwfSendBack.getSortName());
            sbQX.setDealCode(mwfSendBack.getDealCode());
            sbQX.setDealName(mwfSendBack.getDealName());
            sbQX.setSbdeptId(mwfSendBack.getSdeptId());
            sbQX.setSbdeptName(mwfSendBack.getSdeptName());
            sbQX.setSendDesc(mwfSendBack.getSendDesc());
            sbQX.setSendTime(mwfSendBack.getSendTime());
            sbQX.setBackLimit(mwfSendBack.getBackLimit());
            sbQX.setSendRemark(mwfSendBack.getSendRemark());
            sbQX.setSendSpare("1");
            sbQX.setSattachPath(mwfSendBack.getSattachPath());

            SysUser user = ShiroUtils.getSysUser();
            sbQX.setSdeptId(user.getDeptId().toString());
            sbQX.setSdeptName(user.getDeptName());
        }

        try {
            if (mwfSendBack.getFpDirect().equals(1)) {//xnb直派
                mwfSendBackService.save(sbQX);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        MmailWorkForm tworkFormBaseEty = mmailWorkFormService.getById(mwfSendBack.getWfId());
        int row = 0;
        if(mwfSendBack.getSbdeptId().indexOf(',') == -1) {
            mwfSendBack.setSbdeptId(mwfSendBack.getSbdeptId()+",");
            mwfSendBack.setSbdeptName(mwfSendBack.getSbdeptName()+",");
        }
        //拟派多个部门
        if(mwfSendBack.getSbdeptId().indexOf(',') != -1) {
            String[] ids = mwfSendBack.getSbdeptId().split(",");
            String[] names = mwfSendBack.getSbdeptName().split(",");
            String sendDesc = mwfSendBack.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                MwfSendBack etyMain = new MwfSendBack();
                if (tworkFormBaseEty != null) {
                    // TODO: 未完善
                    // 拟派给主办单位  统一为主办单位     协办单位不需要了
                    etyMain.setMailPk(Integer.parseInt(tworkFormBaseEty.getOriginFK()));

                    etyMain.setWfId(Integer.parseInt(tworkFormBaseEty.getPkId()));
                }
                int oriLevel = 1;
                if(!"304".equals(deptId) && deptId.length() == 3)
                    oriLevel = 2;
                else
                    oriLevel = deptId.length() / 3;
                etyMain.setOriLevel(oriLevel);
                etyMain.setSeqCode(mwfSendBack.getSeqCode());
                etyMain.setSeqName(mwfSendBack.getSeqName());
                etyMain.setSendState(10);
                etyMain.setSendDesc(mwfSendBack.getSendDesc());
                etyMain.setSdeptId(mwfSendBack.getSdeptId());
                etyMain.setSdeptName(mwfSendBack.getSdeptName());
                etyMain.setSuserNo(mwfSendBack.getSuserNo());
                etyMain.setSuserName(mwfSendBack.getSuserName());
                etyMain.setSendTime(new Date());
                etyMain.setSendRemark(mwfSendBack.getSendRemark());
                etyMain.setSattachPath(mwfSendBack.getSattachPath());
                etyMain.setSattachName(mwfSendBack.getSattachName());
                etyMain.setSendSpare(mwfSendBack.getSendSpare());
                etyMain.setBackState(0);
                etyMain.setSortCode("11");
                etyMain.setSortName("主办");
                etyMain.setDealCode("11");
                etyMain.setDealName(mwfSendBack.getDealName());
                etyMain.setBackLimit(mwfSendBack.getBackLimit());

                //TODO：promisesTime不清楚怎么来的
                etyMain.setPromisesTime(mwfSendBack.getBackLimit());
                etyMain.setSbdeptId(ids[i]);
                etyMain.setSbdeptName(names[i]);
                boolean flag = mwfSendBackService.save(etyMain);
                if (flag) {
                    row = 1;
                    // 记录电话派单操作日志
                    SysUser user = ShiroUtils.getSysUser();
                    //todo 日志
                    MMailWorkFormLog etyLog = new MMailWorkFormLog();
                    etyLog.setWfId(mwfSendBack.getWfId()); //[tWorkFormBase]PkId
                    etyLog.setOpDeptNo(user.getDeptId().toString());
                    etyLog.setOpDeptName(user.getDeptName());
                    etyLog.setOpUserNo(user.getUserNo());
                    etyLog.setOpUserName(user.getUserName());
                    etyLog.setOpAction("提交初稿");
                    etyLog.setOpBtnID(-1);
                    String temp = "";
                    String desc = "";
                    temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                    if (temp.lastIndexOf(",") > 0)
                        temp = temp.substring(0, temp.length() - 1);
                    desc = "主办：";
                    desc += temp;
                    etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                    etyLog.setWsOpen(1); //website ShowFlag
                    etyLog.setOpDesc("提交到承办单位：" + desc);
                    etyLog.setEffectFlag(1);
                    mMailWorkFormLogService.save(etyLog);
                }
            }
        }
        return toAjax(row);
    }

    public AjaxResult simulacrum_gxq(MwfSendBack mwfSendBack, String zpFlag) {
        SysUser user = ShiroUtils.getSysUser();
        String deptId = user.getDeptId().toString();
        MmailWorkForm tworkFormBaseEty = mmailWorkFormService.getById(mwfSendBack.getWfId());
        MwfSendBack etyMain = new MwfSendBack();
        if (tworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setMailPk(Integer.parseInt(tworkFormBaseEty.getOriginFK()));
            etyMain.setWfId(Integer.parseInt(tworkFormBaseEty.getPkId()));
        }
        int oriLevel = 1;
        if(!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(mwfSendBack.getSeqCode());
        etyMain.setSeqName(mwfSendBack.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(mwfSendBack.getSendDesc());
        etyMain.setSdeptId(mwfSendBack.getSdeptId());
        etyMain.setSdeptName(mwfSendBack.getSdeptName());
        etyMain.setSuserNo(mwfSendBack.getSuserNo());
        etyMain.setSuserName(mwfSendBack.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(mwfSendBack.getSendRemark());
        etyMain.setSattachPath(mwfSendBack.getSattachPath());
        etyMain.setSattachName(mwfSendBack.getSattachName());
        etyMain.setSendSpare(mwfSendBack.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(mwfSendBack.getDealName());
        etyMain.setBackLimit(mwfSendBack.getBackLimit());
        //TODO：promisesTime不清楚怎么来的
        etyMain.setPromisesTime(mwfSendBack.getBackLimit());
        if (mwfSendBack.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (mwfSendBack.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(mwfSendBack.getSbdeptId());
        etyMain.setSbdeptName(mwfSendBack.getSbdeptName());
        Integer pid = mwfSendBack.getPid();
        if(!"304".equals(deptId) && (pid == null || pid <= 0)) {
            //不用每个地方都从页面把pid传够了，容易绕晕，但父id不是百分百准确
            QueryWrapper<MwfSendBack> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("top 1 pkId");
            queryWrapper.eq("wfId", mwfSendBack.getWfId());
            queryWrapper.eq("SBDeptId",getSysUser().getDeptId());
            queryWrapper.orderByDesc("pkId");
            List<MwfSendBack> list = mwfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                pid = list.get(0).getPkId();
            }
        }
        etyMain.setPid(pid);
        int row = 0;
        boolean flag = false;
        //拟派多个部门
        if(mwfSendBack.getSbdeptId().indexOf(',') != -1) {
            String[] ids = mwfSendBack.getSbdeptId().split(",");
            String[] names = mwfSendBack.getSbdeptName().split(",");
            String[] zpFlags = zpFlag.split(",");
            for (int i = 0; i < ids.length; i++) {
                etyMain.setSbdeptId(ids[i]);
                etyMain.setSbdeptName(names[i]);
                etyMain.setSdeptId(mwfSendBack.getSdeptId());
                etyMain.setSdeptName(mwfSendBack.getSdeptName());
                etyMain.setSendDesc("请 "+names[i]+" 调查处理后直接与来话人联系，并将处理结果抄复我办。请注意来话人个人信息保密。");
                etyMain.setPid(pid);
                if (zpFlags[i].equals("10")){
                    etyMain.setSendSpare("1"); //直派
                    flag = manageController.directWF(etyMain);
                }else {
                    flag = mwfSendBackService.save(etyMain);
                }
                if (flag) {
                    row = 1;
                    //todo 日志
                    MMailWorkFormLog etyLog = new MMailWorkFormLog();
                    etyLog.setWfId(mwfSendBack.getWfId()); //[tWorkFormBase]PkId
                    etyLog.setOpDeptNo(user.getDeptId().toString());
                    etyLog.setOpDeptName(user.getDeptName());
                    etyLog.setOpUserNo(user.getUserNo());
                    etyLog.setOpUserName(user.getUserName());
                    etyLog.setOpAction("提交初稿");
                    etyLog.setOpBtnID(-1);
                    String temp = "";
                    String desc = "";
                    temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                    if (temp.lastIndexOf(",") > 0)
                        temp = temp.substring(0, temp.length() - 1);
                    desc = "主办：";
                    desc += temp;
                    etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                    etyLog.setWsOpen(1); //website ShowFlag
                    etyLog.setOpDesc("提交到承办单位：" + desc);
                    etyLog.setEffectFlag(1);
                    mMailWorkFormLogService.save(etyLog);
                }
            }
            //更新父级派单状态 注意mwfSendBack的pkId是插入数据库返回的Id
            commonDao.proMsubBackState(mwfSendBack.getWfId(),etyMain.getPkId());
        }else {
            if (zpFlag != null && zpFlag.equals("0")) {//派给一个部门
                flag = mwfSendBackService.save(etyMain);
            }else {
                //xnb直派
                etyMain.setSendSpare("1"); //直派
                flag = manageController.directWF(etyMain);
            }
            if (flag) {
                row = 1;
                // 记录电话派单操作日志
                MMailWorkFormLog etyLog = new MMailWorkFormLog();
                etyLog.setWfId(mwfSendBack.getWfId()); //[tWorkFormBase]PkId
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                etyLog.setOpAction("提交初稿");
                etyLog.setOpBtnID(-1);
                String temp = "";
                String desc = "";
                temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                if (temp.lastIndexOf(",") > 0)
                    temp = temp.substring(0, temp.length() - 1);
                desc = "主办：";
                desc += temp;
                etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                etyLog.setWsOpen(1); //website ShowFlag
                etyLog.setOpDesc("提交到承办单位：" + desc);
                etyLog.setEffectFlag(1);
                mMailWorkFormLogService.save(etyLog);
            }
            //更新父级派单状态 注意mwfSendBack的pkId是插入数据库返回的Id
            commonDao.proMsubBackState(mwfSendBack.getWfId(),etyMain.getPkId());
        }
        return toAjax(row);
    }


    /**
     * 智能派单
     *
     * @param
     * @return
     */
    @RequestMapping("Intelligent")
    @RepeatSubmit
    public AjaxResult Intelligent(MmailWorkForm workFormBaseEty) throws ParseException {
        SysUser user = ShiroUtils.getSysUser();
        String deptId = user.getDeptId().toString();
        MmailWorkForm formBaseEty = mmailWorkFormService.getById(workFormBaseEty.getPkId());



        MwfSendBack twfSendBackEty = formBaseEty.getMwfSendBack();
        twfSendBackEty.setSbdeptName(workFormBaseEty.getMark());
        String deptNo=commonService.selectDeptShort(twfSendBackEty.getSbdeptName());
        twfSendBackEty.setSbdeptId(deptNo);
        twfSendBackEty.setSdeptId(deptId.toString());
        twfSendBackEty.setSdeptName(user.getDeptName());
        twfSendBackEty.setSuserNo(user.getUserNo());
        twfSendBackEty.setSuserName(user.getUserName());
        twfSendBackEty.setWfId(Integer.parseInt(formBaseEty.getPkId()));
        twfSendBackEty.setMailPk(Integer.parseInt(formBaseEty.getOriginFK()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        twfSendBackEty.setBackLimit(sdf.parse(commonService.getNxetBackLimit(5)));
        twfSendBackEty.setSeqName("初次交办");
        twfSendBackEty.setSeqCode("10");
        twfSendBackEty.setSortCode("11");
        twfSendBackEty.setSortName("主办");
        twfSendBackEty.setDealCode("11");
        twfSendBackEty.setDealName("研究办理");
        twfSendBackEty.setFpDirect(0);
        twfSendBackEty.setSendDesc("请 "+twfSendBackEty.getSbdeptName()+" 调查处理后直接与来话人联系，并将处理结果抄复我办。请注意来话人个人信息保密。");

        MwfSendBack sbDir = new MwfSendBack();
        sbDir = twfSendBackEty;
        sbDir.setSendState(10);  //未签收
        sbDir.setSendSpare("1");
        MwfSendBack sbQX = new MwfSendBack(); //区县政府

        try {
            if (twfSendBackEty.getFpDirect() > 0) {//xnb直派
                mwfSendBackService.save(sbQX);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        MmailWorkForm tworkFormBaseEty = mmailWorkFormService.getById(twfSendBackEty.getWfId());
        MwfSendBack etyMain = new MwfSendBack();
        if (tworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setMailPk(Integer.parseInt(tworkFormBaseEty.getOriginFK()));
            etyMain.setWfId(Integer.parseInt(tworkFormBaseEty.getPkId()));
        }
        int oriLevel = 1;
        if(!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(twfSendBackEty.getSeqCode());
        etyMain.setSeqName(twfSendBackEty.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(twfSendBackEty.getSendDesc());
        etyMain.setSdeptId(twfSendBackEty.getSdeptId());
        etyMain.setSdeptName(twfSendBackEty.getSdeptName());
        etyMain.setSuserNo(twfSendBackEty.getSuserNo());
        etyMain.setSuserName(twfSendBackEty.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(twfSendBackEty.getSendRemark());
        etyMain.setSattachPath(twfSendBackEty.getSattachPath());
        etyMain.setSattachName(twfSendBackEty.getSattachName());
        etyMain.setSendSpare(twfSendBackEty.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(twfSendBackEty.getDealName());
        etyMain.setBackLimit(twfSendBackEty.getBackLimit());
//        bDeptId = arrDetpIdX[i];
//        bDeptName = arrDetpNameX[i];
        if (twfSendBackEty.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (twfSendBackEty.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(twfSendBackEty.getSbdeptId());
        etyMain.setSbdeptName(twfSendBackEty.getSbdeptName());
        int row = 0;
        boolean flag = mwfSendBackService.save(etyMain);
        if (flag) {
            row = 1;
            // 记录电话派单操作日志
            //todo 日志
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(twfSendBackEty.getWfId()); //[tWorkFormBase]PkId
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpAction("提交初稿");
            etyLog.setOpBtnID(-1);
            String temp = "";
            String desc = "";
            temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
            if (temp.lastIndexOf(",") > 0)
                temp = temp.substring(0, temp.length() - 1);
            desc = "主办：";
            desc += temp;
            etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
            etyLog.setWsOpen(1); //website ShowFlag
            etyLog.setOpDesc("提交内容概要：" + desc);
            etyLog.setEffectFlag(1);
            mMailWorkFormLogService.save(etyLog);
        }
        return toAjax(row);
    }


    /**
     * 拟派工单 列表显示
     *
     * @param
     * @param
     * @return
     */
    @GetMapping("/simulacrumList/{wfId}")
    public ModelAndView simulacrumLists(@PathVariable("wfId") Integer wfId,ModelMap map) {
        map.put("wfId",wfId);
        return new ModelAndView(prefix+"/simulacrumList");
    }
    /**
     * 拟派工单 列表显示
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("simulacrumList/{wfId}")
    public TableDataInfo simulacrumList(@PathVariable("wfId") Integer wfId) {
        startPage();
        List<MwfSendBack> list = mwfSendBackService.selectByWfId(wfId+"");
        return getDataTable(list);
    }
    @GetMapping("/mailDetail/{pkId}")
    public ModelAndView mailDetail(@PathVariable Integer pkId,ModelMap map){
        map.put("mailSendBack",mwfSendBackService.getById(pkId));
        return  new ModelAndView(prefix+"/mailDetail");
    }

    /**
     * 根据id 进行多选删除 和单个删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String... ids) {
        return toAjax(mwfSendBackService.deleteByIds(ids));
    }


    /**
     * 进入修改拟派工单的页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/editDept/{wfId}/{pkId}")
    public ModelAndView editDept(@PathVariable("wfId") Integer wfId, @PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        MmailWorkForm tworkFormBaseEty = mmailWorkFormService.getById(wfId);
        MwfSendBack sendBackEty = mwfSendBackService.getById(pkId);
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        tworkFormBaseEty.setMwfSendBack(sendBackEty);
        map.put("workFormBase", tworkFormBaseEty);
        map.put("twfSendBackEty", sendBackEty);
        map.put("wfId", tworkFormBaseEty.getPkId());
        map.put("sdeptName", sendBackEty.getSdeptName());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());

        return new ModelAndView(prefix+"/editDeptDiag");
    }

    /**
     * 修改拟派工单信息
     * @param mmailWorkForm 带有拟派工单的信件工单
     * @return 响应结果
     */
    @PostMapping("/editDept")
    public AjaxResult editDept(MmailWorkForm mmailWorkForm) {
        //保存响应结果
        boolean flag = false;
        MwfSendBack mwfSendBack = mmailWorkForm.getMwfSendBack();
        if (mwfSendBack.getPkId() > 0) {
            UpdateWrapper<MwfSendBack> sbWrapper = new UpdateWrapper<>();
            sbWrapper
                    .set("SeqCode", mwfSendBack.getSeqCode())
                    .set("SeqName", mwfSendBack.getSeqName())
                    .set("SbdeptId", mwfSendBack.getSbdeptId())
                    .set("SbdeptName", mwfSendBack.getSbdeptName())
                    .set("SortCode", mwfSendBack.getSortCode())
                    .set("SortName", mwfSendBack.getSortName())
                    .set("DealCode", mwfSendBack.getDealCode())
                    .set("DealName", mwfSendBack.getDealName())
                    .set("SendDesc", mwfSendBack.getSendDesc())
                    .set("BackLimit", mwfSendBack.getBackLimit())
                    .set("SendRemark", mwfSendBack.getSendRemark())
                    .eq("PkId", mwfSendBack.getPkId());
            //执行修改方法
            flag = mwfSendBackService.update(sbWrapper);
            //判断是否修改成功
            if (flag) {
                // 记录信件派单操作日志
                SysUser user = ShiroUtils.getSysUser();
                MMailWorkFormLog etyLog = new MMailWorkFormLog();
                //[tWorkFormBase]PkId
                etyLog.setWfId(mwfSendBack.getWfId());
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                String temp = "调整办理部门及要求(" + mwfSendBack.getSbdeptName() + ")";
                etyLog.setOpAction("修改");
                etyLog.setOpBtnID(-1);
                etyLog.setWsDesc(temp);
                etyLog.setWsOpen(1);
                etyLog.setOpDesc(temp);
                etyLog.setEffectFlag(-1);
                mMailWorkFormLogService.save(etyLog);
            }
        }
        return toAjax(flag);
    }

    private  String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public String byTelGetSN(int fpLen)
    {
        String rtn = "2";
        String tmpNO = ""; String tmpStr = "";
        String cYear = ""; String cMth = ""; String cDay = "";
        String rYear = ""; String rMth = ""; String rDay = "";
        int tmpInt = -1;
        Calendar myDay = Calendar.getInstance();

        tmpInt = myDay.get(1);
        cYear = String.valueOf(tmpInt);
        tmpInt -= 2000;
        rYear = String.valueOf(tmpInt);

        tmpInt = myDay.get(2) + 1;
        cMth = String.valueOf(tmpInt);
        if (tmpInt < 10)
            rMth = "0" + cMth;
        else {
            rMth = cMth;
        }
        tmpInt = myDay.get(5);
        cDay = String.valueOf(tmpInt);
        if (tmpInt < 10)
            rDay = "0" + cDay;
        else {
            rDay = cDay;
        }
        tmpInt = mailGetDealService.countSNbyDate(cYear, cMth, cDay);
        tmpInt++;
        tmpNO = Integer.toString(tmpInt);
        if (tmpNO.length() >= fpLen) {
            tmpStr = tmpNO;
        }
        else {
            String zeroPre = "";
            for (int i = 0; i < fpLen - tmpNO.length(); i++) {
                zeroPre = zeroPre + "0";
            }
            tmpStr = zeroPre + tmpNO;
        }

        rtn = rtn + rYear + rMth + rDay + tmpStr;
        return rtn;
    }

    /**
     * 查看附件
     * @param wsCode 流水号
     * @param fileName 文件名
     */
    @GetMapping("/chkFile")
    public void chkFile(String wsCode,String fileName, HttpServletResponse resp) throws IOException{
        if(fileName.endsWith(".jpg")
                || fileName.endsWith(".jpeg")){
            resp.setContentType("image/jpeg");
        }else if(fileName.endsWith(".png")){
            resp.setContentType("image/png");
        }else if(fileName.endsWith(".gif")){
            resp.setContentType("image/gif");
        }else if(fileName.endsWith(".pdf")){
            resp.setContentType("appliction/pdf");
            resp.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }else if(fileName.endsWith(".doc")){
            resp.setContentType("application/msword");
            resp.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }else if(fileName.endsWith(".txt")){
            resp.setContentType("text/plain");
        }else if(fileName.endsWith(".xls")){
            resp.setContentType("application/x-xls");
            resp.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }else if(fileName.endsWith(".ppt")){
            resp.setContentType("application/vnd.ms-powerpoint");
            resp.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }else {
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }
        resp.setCharacterEncoding("utf-8");
        try {
            byte[] bytes = FileTools.getAccessoryByName(wsCode,fileName);
            OutputStream os = resp.getOutputStream();
            os.write(bytes);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 呈批信件 合并后台自建信件和网络理政件
     * @param approvalVO
     * @return
     */
    @PostMapping("/forApproval")
    public AjaxResult transfer(ApprovalVO approvalVO) {
        AjaxResult ajaxResult = AjaxResult.success();
        MmailGetDealEty mmailGetDeal = mailGetDealService.getById(approvalVO.getPkId());
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String judge = null;
        int count = 0;
        String tsql = "select swift_number from t_ticket where import_id=" + approvalVO.getPkId();
        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(tsql);
            rs = ps.executeQuery();
            while (rs.next()) {
                judge = rs.getString(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.error();
        } finally {
            DBUtil.closeConnection();
        }
        if (judge == null) {
//                String sql = "insert into t_ticket(import_id,import_at,title,swift_number,body,address,area,email,phone_no,author_name,sent_at,help_category,content_category,owner,out_type) values('" +
//                        pkId + "','" + inputDate + "','" + FromTopic + "','" + WsCode + "','" + FmContent + "','" + FmAddress + "','" + ddlArea + "','" + FmEmail + "','" + FromTel + "','" + FromName + "','" + FromTime + "','" + ddlTelSort + "','" + txtDcntAcode + "','" + FmSpare + "',2)";
            String sql = "insert into t_ticket(import_id,import_at,title,swift_number,body,address,area,email,phone_no,author_name,sent_at,help_category,content_category,owner,out_type) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,2)";
            try {
                Date date = new Date();
                SimpleDateFormat dqTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String inputDate = dqTime.format(date);
                conn = DBUtil.getConnection();
                String fmSpareStr = mmailGetDeal.getFmSpare();
                if(StringUtils.isNotEmpty(fmSpareStr)) {
                    Integer mailboxId = Integer.valueOf(fmSpareStr);
                    //网络理政件小于50000 大于50000后台自建信件
                    if(mailboxId < 50000) {
                        approvalVO.setMailboxNo(fmSpareStr);
                    }
                }
                ps = conn.prepareStatement(sql);
                ps.setInt(1, approvalVO.getPkId());
                ps.setString(2, inputDate);
                ps.setString(3, mmailGetDeal.getFromTopic());
                ps.setString(4, mmailGetDeal.getWsCode());
                ps.setString(5, mmailGetDeal.getFmContent());
                ps.setString(6, mmailGetDeal.getFmAddress());
                ps.setString(7, approvalVO.getDdlArea());
                ps.setString(8, mmailGetDeal.getFmEmail());
                ps.setString(9, mmailGetDeal.getFromTel());
                ps.setString(10, mmailGetDeal.getFromName());
                ps.setObject(11, mmailGetDeal.getFromTime());
                ps.setString(12, approvalVO.getDdlTelSort());
                ps.setString(13, approvalVO.getTxtDcntAcode());
                ps.setString(14, approvalVO.getMailboxNo());
                count = ps.executeUpdate();
                System.out.println("count=" + count);
                UpdateWrapper<MmailGetDealEty> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().eq(MmailGetDealEty::getPkId, approvalVO.getPkId())
                        .set(MmailGetDealEty::getFlagString, approvalVO.getFlagString());
                mailGetDealService.update(updateWrapper);
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.error();
            } finally {
                DBUtil.closeConnection();
            }
        }
        return ajaxResult;
    }


    /**
     * 未回复呈批信件
     */
    @PostMapping("/notReplayForApproval")
    public AjaxResult notReplayForApproval(ApprovalVO approvalVO){
        AjaxResult ajaxResult = transfer(approvalVO);
        UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("FlagString",approvalVO.getFlagString());
        updateWrapper.eq("PkId",approvalVO.getWfId());
        mmailWorkFormService.update(updateWrapper);
        return ajaxResult;
    }

    /**
     * 打印督办单
     * @param ids 派单编号
     * @return 页面
     */
    @GetMapping("/printSends")
    public ModelAndView printSends(String ids, HttpServletRequest request){
        ModelAndView mav = new ModelAndView(prefix+"/printSends");
        String[] idList = ids.split(",");
        List<MmailGetDealEty> list = new ArrayList<>();
        for (String id : idList) {
            MmailGetDealEty mailDeal = mailGetDealService.getById(id);
            list.add(mailDeal);
        }
        mav.addObject("sends",list);
        String WsCode = list.get(0).getWsCode();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List PsList = null;
        String tsql = "select body,type,user_id,created_at from t_handle_note where ticket_id in (select id from t_ticket where swift_number='" + WsCode + "')";
        try {
            PsList = new ArrayList();
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(tsql);
            rs = ps.executeQuery();
            if(rs.next()) {
                PsList.add(createEntity(rs));
            }
            request.setAttribute("PsList", PsList);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection();
        }
        return mav;
    }

    private InstructionsEntity createEntity(ResultSet rs) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet reset = null;
        String type = null;
        int flag = rs.getInt(2);
        if (flag == 0)
            type = "转派";
        else if (flag == 1)
            type = "批示";
        else if (flag == 2)
            type = "备注";
        else if (flag == 3) {
            type = "意见";
        }
        int user_id = rs.getInt(3);
        String userName = null;
        String tsql = "select realname from t_user where id=" + user_id;
        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(tsql);
            reset = ps.executeQuery();
            while (reset.next())
                userName = reset.getString(1);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

        InstructionsEntity entity = new InstructionsEntity();
        entity.setBody(rs.getString(1));
        entity.setType(type);
        entity.setUserName(userName);
        entity.setCreated_at(rs.getDate(4));

        return entity;
    }


    /**
     * 本单位网络理政件列表页
     * @return
     */
    @RequestMapping("/netMailWF")
    public ModelAndView netMailWFPage() {
        return new ModelAndView(prefix + "/netMailWF");
    }

    /**
     * 本单位网络理政件列表数据
     * @return
     */
    @RequestMapping("/netMailWFJson")
    public TableDataInfo netMailWFJson(QueryConditionVo queryConditionVo) {
        SysUser user = getSysUser();
        String sbDeptId = null;
        if(user.getDeptId() != null) {
            sbDeptId= user.getDeptId().toString();
        }
        startPage();
        List<Map<String, Object>> list = mmailWorkFormService.netMailWFListJson(sbDeptId,queryConditionVo);
        return getDataTable(list);
    }

    /**
     * 本单位网络理政件数据导出(网络理政区县）
     * @return
     */
    @PostMapping("/netMailWF/export")
    @ResponseBody
    public AjaxResult netMailWFExport(QueryConditionVo queryConditionVo) {
        SysUser user = getSysUser();
        String sbDeptId = null;
        if(user.getDeptId() != null) {
            sbDeptId= user.getDeptId().toString();
        }
        List<MailExcel> netMailWFList = mmailWorkFormService.netMailWFListExport(sbDeptId,queryConditionVo);
        ExcelUtil<MailExcel> util = new ExcelUtil<>(MailExcel.class);
        return util.exportExcel(netMailWFList, user.getDeptName()+"网络理政信件工单数据");
    }

    /**
     * 本单位网络理政件数据不满意件导出(网络理政区县）
     * @return
     */
    @PostMapping("/UnsatisfyNetMailWF/export")
    @ResponseBody
    public AjaxResult UnsatisfyNetMailWFExport(QueryConditionVo queryConditionVo) {
        SysUser user = getSysUser();
        String sbDeptId = null;
        if(user.getDeptId() != null) {
            sbDeptId= user.getDeptId().toString();
        }
        List<MailExcel> list = mmailWorkFormService.netMailWFListExport(sbDeptId,queryConditionVo);
        //不满意件
        list = list.stream().filter(f->f.getJudgeC()!=null).filter(f->f.getJudgeC().equals("1")).filter(f->f.getGroupIndex() == 1).collect(Collectors.toList());
        ExcelUtil<MailExcel> util = new ExcelUtil<>(MailExcel.class);
        if (list.size()>0) {
            return util.exportExcel(list, user.getDeptName()+"网络理政不满意信件工单数据");
        } else {
            return new AjaxResult(AjaxResult.Type.ERROR,"暂无不满意信件工单数据！");
        }
    }

    @GetMapping("/submitForApproval")
    public ModelAndView submitForApproval(ModelMap map){
        return new ModelAndView( prefix + "/submitForApproval");
    }

    @PostMapping("/submitForApprovalJson")
    public TableDataInfo submitForApprovalJson(){
        SysUser user = getSysUser();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> listData = new ArrayList<>();
        String submitSql = "select t2.id submit_id,t2.name,t2.job_title_name submit_name from t_organ_structure t1 inner join t_mail_box t2 on t1.id=t2.organ_id where DeptNo=" + user.getDeptId() + " ORDER BY job_hierarchy ";
        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(submitSql);
            rs = ps.executeQuery();
            ResultSetMetaData data = rs.getMetaData();
            int dataColumnCount = data.getColumnCount();
            while (rs.next()) {
                Map<String, Object> resData = new HashMap<>();
                for (int i = 1; i <= dataColumnCount ; i++) {
                    resData.put(data.getColumnLabel(i),rs.getObject(i));
                }
                listData.add(resData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection();
        }
        return getDataTable(listData);
    }
}
